package com.wuzihao.disk.login.control;

import com.wuzihao.disk.mybatis.entity.PtUserEntity;
import com.wuzihao.disk.login.service.LoginService;
import com.wuzihao.disk.user.service.UserService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/login")
public class LoginControl {

    @Resource
    private HttpSession httpSession;

    @Resource
    private LoginService loginService;

    @Resource
    private UserService userService;
    @RequestMapping("/login")
    //有改动从@---request
    public String loginPage(HttpServletRequest request, Model model){
        httpSession.setAttribute("lang", LocaleContextHolder.getLocale().toString());

        // 获取错误次数
        Integer errorCount = (Integer) request.getSession().getAttribute("loginErrorCount");
        model.addAttribute("showCaptcha", errorCount != null && errorCount >= 3);



        return "login/loginPage";

    }



    @RequestMapping("/main")
    public String mainPage(){
        return "redirect:/";
    }

    @RequestMapping("/forgotPassword")
    public String forgotPasswordPage(HttpServletRequest request){
        httpSession.setAttribute("lang", LocaleContextHolder.getLocale().toString());
        return "login/forgotPasswordPage";
    }

    /**
     * 发送验证码
     */
    @RequestMapping(value = "/sendVerifyCode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> sendVerifyCode(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 查询用户信息
            PtUserEntity user = loginService.queryUserInfoByName(username);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }

            // 生成验证码
            String verifyCode = generateVerifyCode();

            // 存储验证码到session，有效期5分钟
            httpSession.setAttribute("verifyCode", verifyCode);
            httpSession.setAttribute("verifyCodeExpire", System.currentTimeMillis() + 5 * 60 * 1000);
            httpSession.setAttribute("username", username);

            // 发送邮件（这里只是模拟，实际项目中需要调用邮件服务）
            System.out.println("发送验证码到用户邮箱: " + user.getEmail() + "，验证码: " + verifyCode);

            result.put("success", true);
            result.put("message", "验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "发送验证码失败");
        }
        return result;
    }

    /**
     * 重置密码
     */
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> resetPassword(@RequestParam String verifyCode, @RequestParam String newPassword) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证验证码
            String storedVerifyCode = (String) httpSession.getAttribute("verifyCode");
            Long verifyCodeExpire = (Long) httpSession.getAttribute("verifyCodeExpire");
            String username = (String) httpSession.getAttribute("username");

            if (storedVerifyCode == null || verifyCodeExpire == null || username == null) {
                result.put("success", false);
                result.put("message", "请先获取验证码");
                return result;
            }

            if (System.currentTimeMillis() > verifyCodeExpire) {
                result.put("success", false);
                result.put("message", "验证码已过期，请重新获取");
                return result;
            }

            if (!verifyCode.equals(storedVerifyCode)) {
                result.put("success", false);
                result.put("message", "验证码错误");
                return result;
            }

            // 重置密码
            PtUserEntity user = loginService.queryUserInfoByName(username);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }

            user.setPassword(newPassword); // 实际项目中应该加密密码
            userService.modifyUserInfoById(user);

            // 清除session中的验证码
            httpSession.removeAttribute("verifyCode");
            httpSession.removeAttribute("verifyCodeExpire");
            httpSession.removeAttribute("username");

            result.put("success", true);
            result.put("message", "密码重置成功，请登录");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "重置密码失败");
        }
        return result;
    }

    /**
     * 生成6位数字验证码
     */
    private String generateVerifyCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}
